<?php

declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\Department as DepartmentModel;
use app\admin\common\ServiceResponse;
use app\admin\model\Operator as ModelOperator;
use app\facade\Basic;

class Department extends BaseService
{

    use ServiceResponse;

    protected $model;
    public function __construct()
    {
        parent::__construct();
        $this->model = new DepartmentModel();
    }

    /**
     * @describe 获取部门列表
     * @author: Bobo
     * @date: 2024-06-05 18:02:26
     * @param [] type
     * @return Renderable
     */
    public function getList(array $where, int $page, int $limit)
    {

        if (0 >= $page || 100 < $limit) {
            return $this->error(100002);
        }

        $total = DepartmentModel::where($where)->count();

        $list = DepartmentModel::with(['parentDepartment','get_creator_name','get_update_name'])
            ->where($where)
            ->page($page, $limit)
            ->select();

        if (empty($list)) {
            $data = ['list' => $list, 'total' => $total];
            return $this->success($data);
        }

        $list = $list->toArray();

        $list = array_map(function ($item) {

            if ($item['pid'] == 0) {
                $item['pid'] = null;
            }

            return $item;

        },$list);

        $data = ['list' => $list, 'total' => $total];
        return $this->success($data);
    }


    /**
     * 获取部门详情
     * @param int $id 部门ID
     */
    public function getOneById($id)
    {
        $Department = DepartmentModel::find($id);
        if ( $Department->pid == '0' ) {
            $Department->pid = null;
        }

        if ($Department) {
            $data = $Department->append(['creator_value', 'updater_value',]);
        }

        $data = $data->toArray();
        return $this->success($data);
    }

    /**
     * 创建部门
     * @param array $data 创建部门的数据
     */
    public function create($data)
    {

        try {
            $res = DepartmentModel::find([
                'name' => $data['name'],
                'is_del' => 0
            ]);
            if ($res) {
                return $this->error(100300);
            }
            $result = DepartmentModel::create($data);
            if ($result) {
                $this->logger->logOperation($result->id,'Department','创建','创建部门');
                return $this->success();
            } else {
                return $this->error(500001);
            }
        } catch (\Throwable $th) {
            return $this->error(500001, '服务器内部错误：' . $th->getMessage());
        }
    }

    /**
     * 更新部门
     * @param int $id 部门ID
     * @param array $data 更新部门的数据
     */
    public function update($data)
    {
        $res = DepartmentModel::where('id', $data['id'])->find();

        if (!$res) {
            return false;
        }
        foreach ($data as $key => $value) {
            if ($res->$key != $value) {
                $res->$key = $value;
            }
        }

        $res->update_time = date("Y-m-d H:i:s",time());

        $result = $res->save();
        if ($result) {
            $this->logger->logOperation($data['id'], 'Department', '更新', '更新部门');
            return $this->success();
        } else {
            return $this->error(500001);
        }
    }

    /**
     * 删除部门
     * @param int $id 部门ID
     */
    public function delete($id)
    {
        $this->logger->logOperation($id, 'Department', '删除', '删除部门');
        return DepartmentModel::where('id', $id)->delete();
    }

    function findChildIds($array, $id) {
        $childIds = [];
        foreach ($array as $item) {
            if ($item['pid'] == $id) {
                $childIds[] = $item['id'];
                $childIds = array_merge($childIds, $this->findChildIds($array, $item['id']));
            }
        }
        return $childIds;
    }

    /**
     * @describe 批量逻辑删除部门
     * @author: Bobo
     * @date: 2024-06-26 14:53:00
     * @param [arr] @required $ids ID数组
     * @return Renderable
     */
    public function batchLogicalDelete($params)
    {

        $department = $this->model::where('is_del','0')->field('id,pid,name')->select();
        if (empty($department)) {
            return Basic::data(1,'没有部门数据');
        }

        // 判断是否为空
        $ids = $this->findChildIds($department->toArray(),$params['ids']);
        if ( count($ids) >= 1 ) {
            return Basic::data(1,'存在子部门,无法删除！');
        }

        /* 该部门下存在用户 */
        $operator = ModelOperator::where('department',$params['ids'])->where('is_del',0)->find();
        if ( $operator ) {
            return Basic::data(1,'部门存在用户,无法删除！');
        }

        try {
            $this->model::where('id', $params['ids'])->update(
                [
                    'is_del' => time(),
                    'updater'=>$params['operator_id'],
                    'update_time' => date("Y-m-d H:i:s",time())
                ]);

            $this->logger->logOperation($ids, 'Department', '逻辑删除', '逻辑删除部门');

            return Basic::data(0,'删除成功');
        } catch (\Throwable $th) {
            return Basic::data(1,'删除失败');
        }





    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2024-08-06 19:08:17
     * @param [type] @required
     * @return Renderable
     */
    /**
     * @describe
     * @author: Bobo
     * @date: 2024-07-23 10:34:00
     * @param [type] @required
     * @return Renderable
     */
    public function getFieldEnum($field)
    {
        $model = new DepartmentModel();
        $res = $model->getFieldEnum($field);
        return [
            'code' => 0,
            'data' => $res
        ];
    }

    /**
     * @describe 获取部门树形结构
     * @author: Bobo
     * @date: 2024-09-12 18:02:20
     * @param [type] @required
     * @return Renderable
     */
    public function getTreeSelectOption($pid = 0)
    {


        // 获取所有部门
        $result = DepartmentModel::where(['is_del' => 0, 'status' => 1])->field('id,pid as parent_id,name')->select();

        if ( !$result ) {
            return [
                'code' => 0,
                'data' => [
                    'list' => []
                ]
            ];
        }

        $data = $result->toArray();

        $listTreeData =  $this->listTree($data,0);

        return [
            'code' => 0,
            'data' => [
                'list' => $listTreeData
            ]
        ];

    }



    /**
     *  权限菜单递归处理
     */
    public function listTree(array $data, $parent_id = 0) {

        $branch = [];
        foreach ($data as $value) {
            $element = [];
            $element['id'] = $value['id'];
            $element['name'] = $value['name'];
            $element['parent_id'] = $value['parent_id'];
            if ($value['parent_id'] == $parent_id) {
                $children = $this->listTree($data, $value['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }
        return $branch;
    }





    /**
     * @describe    获取部门ID数组
     * @author: Bobo
     * @date: 2024-09-13 14:02:00
     * @param [type] @required
     * @return Renderable
     */
    public function getAllDepartmentId($pid = 0, $where = ['is_del' => 0, 'status' => 1])
    {
        $model = new DepartmentModel();
        $departmentIdarr = $model->getAllDepartmentId($pid, $where);
        return $this->success(['list' => $departmentIdarr]);
    }
}
